<?php
namespace apiadmin\modules\v1\controllers\member; 
use apiadmin\modules\v1\controllers\CoreController;

use common\models\Member;
use common\models\StaticInstance;
use \Yii;
use common\utils\OutputExecl;
use common\models\GroupDetail;
use common\models\TradeCommodity;

/**
* 订单相关控制器
*/

class MemberController extends CoreController
{
	/*
		*会员列表
	*/
	public function actionMemberList()
	{

		$where  = $this->formartWhere();
		$params = array(
			'field'	=> ['member_id','member_name','member_mobile','invite_id','member_avatar','grade','state',
			'create_time','update_time','member_email','m_grade'],
			'order' => 'member_id desc',
			'page'	=> $this->request('page','1'),
			'limit' => $this->request('page_size',10),
		);
            $list =Member::MemberList($where,$params,['inviter','team_total','group','order']);
		$pages = Member::$pages;

		$investGrade = \Yii::$app->params['investGrade'];
		$this->out('会员列表',$list,array('pages'=>$pages,'investGrade'=>$investGrade));
	}

	//组装条件
	public function formartWhere()
	{
		$where = [];
		$whereAnd = [];
		$searchKeys = json_decode($this->request('search'),1);

		if(!$searchKeys) return array('where'=>$where,'whereAnd'=>$whereAnd);
		foreach($searchKeys as $k=>$val)
		{
			if(!$val) continue;
			if($k=='date')
			{
				if(!$val['0'] || !$val['1']) continue;
				$whereAnd[] = ['between', 'create_time', strtotime($val[0]),strtotime($val[1])]; 
			}elseif ($k=='member_name') {
				$whereAnd[] = ['like',$k,$val];
			}else
			{
				$where[$k] = $val;
			}
		}

		return array('where'=>$where,'whereAnd'=>$whereAnd);
	}	


	/*
		删除会员
		member_id
	*/
	public function actionMemberDel()
	{
		if(!$memberId = $this->request('member_id')) $this->error('参数错误');
		$res = Member::MemberDel($memberId);
		if($res) $this->out('删除成功');
		$this->error('删除失败');
	}

	/*
		获取单个会员信息
		* member_id 会员ID
	*/
	public function actionMemberInfo()
	{
		if(!$memberId = $this->request('member_id')) $this->error('参数错误');
		$field  = ['*'];
		$member = Member::getMemberById($memberId,$field);
		$this->out('会员信息',$member);
	}

	/*
		通过id或是电话 搜索会员信息
		* member 
	*/
	public function actionQueryMember()
	{
		if(!$memberKey = $this->request('member_key')) $this->error('参数错误');
		$field  = ['member_id','member_name','member_mobile'];
		$member = Member::queryMember($memberKey,$field);
		$this->out('会员信息',$member);		
	}



	//会员信息修改
	public function actionMemberEdit()
	{
		$params = $this->request;

		if($params['loginpwd'])
			$params['loginpwd'] = md5($params['loginpwd']);
		else
			unset($params['loginpwd']);

		if($params['paypwd'])
			$params['paypwd'] = md5($params['paypwd']);
		else
			unset($params['paypwd']);		

		$memberModel = $this->model('Member',$params,'',$this->request('member_id'));
		$memberModel->update_time = time();
		if(!$memberModel->save(false)) $this->error('修改失败');  
		$this->out('修改成功');
	}


	//会员添加
	public function actionMemberAdd()
	{
		$params = $this->request;

		$memberModel = $this->model('Member',$params,'',$this->request('member_id'));
		$memberModel->loginpwd = md5($memberModel->loginpwd);
		$memberModel->paypwd = md5($memberModel->paypwd);
		$memberModel->auth_key = Yii::$app->security->generateRandomString(); 
		$memberModel->create_time = time();
		if(!$memberModel->save(false)) $this->error('添加失败');  
		$this->out('添加成功');
	}


      public  function actionExports()
    {
        $data = StaticInstance::find()->asArray()->all();
        $memberId = array_unique(array_column($data, 'commodity_id'));
        /**/
        $commodityInfo = TradeCommodity::getAll(['commodity_id' => $memberId], 'day_income,commodity_id');
        $commodity = [];

        foreach ($commodityInfo as $gk => $gv) {
            $commodity[$gv['commodity_id']] = $gv['day_income'];
        }
        foreach ($data as $k => &$val) {
            $val['day_money'] = bcmul($val['total_num'], $commodity[$val['commodity_id']], 4) / 100;
            $val['count_money'] = bcmul(bcmul($val['in_num'], $commodity[$val['commodity_id']], 4) / 100, $val['period_day']);
            $val['leiji_money'] = bcmul(bcmul($val['in_num'], $commodity[$val['commodity_id']], 4) / 100, $val['bonus_day']);
            $val['end_time'] = date("Y-m-d", strtotime("+" . $val['period_day'] . " day", $val['create_time']));
            $val['start_time'] = date('Y-m-d', $val['create_time']);
            $val['day_income'] = $commodity[$val['commodity_id']];
        }
        $exportData = array();
        foreach ($data as $val) {

            $temp = [];
            $temp[] = $val['member_id'];
            $temp[] = $val['id'];
            $temp[] = '';
            $temp[] = '';
            $temp[] = $val['in_num'];
            $temp[] = $val['count_money'];
            $temp[] = $val['leiji_money'];
            $temp[] = $val['day_money'];
            $temp[] = $val['period_day'];
            $temp[] = $val['bonus_day'];
            $temp[] = $val['start_time'];
            $temp[] = $val['end_time'];
            $temp[] = $val['status']==1?'0':1;
            $temp[] = $val['day_income'];
            $temp[] = $val['start_time'];
            
            $exportData[] = $temp;
        }
        $headData = array('A1' => '用户id', 'B1' => '合约id', 'C1' => '合约名称',
            'D1' => '订单编码', 'E1' => '合约金额', 'F1' => '预计收益', 'G1' => '累计收益',
            'H1' => '昨日收益','I1'=>'合约天数','J1'=>'收益天数','K1'=>'起息时间','L1'=>'到期时间',
            'M1'=>'状态(0进行中 1已到期)','N1'=>'收益利率(‰)','O1'=>'创建时间');
        $fileName = '合约表.xls';
        $execlObj = new OutputExecl();
        $res = $execlObj->output($headData, $exportData, $fileName);
        if ($res)
            $this->out('下载地址', array('url' => $res));
        else
            $this->error('导出失败');
    }
	//会员导出
	public function actionExport()
	{
		$where  = $this->formartWhere();
		$params = array(
			'field'	=> ['member_id','member_name','member_mobile','invite_id','grade','state',
			'create_time','update_time',],
			'order' => 'member_id desc',
			'page'	=> $this->request('page','1'),
			'limit' => $this->request('page_size',10),
		);
		$list = Member::MemberList($where,$params,['infos']);
	
		//组织导出数据
		$exportData = array();
		foreach($list as $val)
		{

			$temp = [];
			$temp[] = $val['member_id'];
			$temp[] = $val['member_name'];
			$temp[] = $val['member_mobile'];
			$temp[] = $val['state']?'正常':'冻结';
			$temp[] = date("Y-m-d H:i:s",$val['create_time']);
			$temp[] = $val['invite_id'];
			$temp[] = $val['money'];
			$exportData[] = $temp;
		}
		$headData = array('A1'=>'会员ID','B1'=>'会员姓名','C1'=>'会员电话','D1'=>'会员状态','E1'=>'注册时间','F1'=>'上级ID','G1'=>'USDT');
		$fileName = 'member-'.date('Y-m-d').'.xls';
		$execlObj = new OutputExecl();
		$res = $execlObj->output($headData,$exportData,$fileName);
		if($res)
			$this->out('下载地址',array('url'=>$res));
		else
			$this->error('导出失败');
	}


	## 会员结构图
	public function actionMemberTree()
	{
		$pid = $this->request('pid',0);
		$where = ['invite_id'=>$pid];
		$field = ['member_id','member_name','member_mobile','member_email','grade'];
		$data = Member::find()->select($field)->where($where)->asarray()->all();
		if(!$data) $this->out('会员列表',$data);
		foreach($data as &$val){
			$nums = Member::find()->where(['invite_id'=>$val['member_id']])->count();
			$val['money_num'] = StaticInstance::find()->where(['member_id'=>$val['member_id']])->sum('in_num');
			$val['leaf'] = $nums>0?false:true;
		}
		$this->out('会员列表',$data);
	}

	public function actionSearchMember()
	{
		if(!$memberKey = $this->request('member_key')) $this->error('参数错误');
		$field = ['member_id','member_name','member_mobile','member_email','grade'];
		$where = ['or','member_id="'.$memberKey.'"','member_email="'.$memberKey.'"'];
		$data = Member::find()->select($field)->where($where)->asarray()->all();
		if(!$data) $this->out('会员信息',$data);
		
		foreach($data as &$val){
			$nums = Member::find()->where(['invite_id'=>$val['member_id']])->count();
			$val['leaf'] = $nums>0?false:true;
		}		
		$this->out('会员信息',$data);		
	}	


}